<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>珠峰架构师成长计划</title>
    <link rel="stylesheet" type="text/css" href="../static/css/main.css">
</head>
<body>
<div class="nav">
    <div class="logo">
        
            珠峰架构师成长计划
        
    </div>
<ul><li><a href="../index.html">0.Async</a></li><li><a href="../html/0.editor.html">0.editor</a></li><li><a href="../html/0.module.html">0.module</a></li><li><a href="../html/1.ES2015.html">1.ES2015</a></li><li><a href="../html/2.Promise.html">2.Promise</a></li><li><a href="../html/3.Node.html">3.Node</a></li><li><a href="../html/4.NodeInstall.html">4.NodeInstall</a></li><li><a href="../html/5.REPL.html">5.REPL</a></li><li><a href="../html/6.NodeCore.html">6.NodeCore</a></li><li><a href="../html/7.module&NPM.html">7.module&NPM</a></li><li><a href="../html/8.Encoding.html">8.Encoding</a></li><li><a href="../html/9.Buffer.html">9.Buffer</a></li><li><a href="../html/10.fs.html">10.fs</a></li><li><a href="../html/11.Stream-1.html">11.Stream-1</a></li><li><a href="../html/11.Stream-2.html">11.Stream-2</a></li><li><a href="../html/11.Stream-3.html">11.Stream-3</a></li><li><a href="../html/11.Stream-4.html">11.Stream-4</a></li><li><a href="../html/12-Network-2.html">12-Network-2</a></li><li><a href="../html/12.NetWork-3.html">12.NetWork-3</a></li><li><a href="../html/12.Network-1.html">12.Network-1</a></li><li><a href="../html/13.tcp.html">13.tcp</a></li><li><a href="../html/14.http-1.html">14.http-1</a></li><li><a href="../html/14.http-2.html">14.http-2</a></li><li><a href="../html/15.compress.html">15.compress</a></li><li><a href="../html/16.crypto.html">16.crypto</a></li><li><a href="../html/17.process.html">17.process</a></li><li><a href="../html/18.yargs.html">18.yargs</a></li><li><a href="../html/19.cache.html">19.cache</a></li><li><a href="../html/20.action.html">20.action</a></li><li><a href="../html/21.https.html">21.https</a></li><li><a href="../html/22.cookie.html">22.cookie</a></li><li><a href="../html/23.session.html">23.session</a></li><li><a href="../html/24.express-1.html">24.express-1</a></li><li><a href="../html/24.express-2.html">24.express-2</a></li><li><a href="../html/24.express-3.html">24.express-3</a></li><li><a href="../html/24.express-4.html">24.express-4</a></li><li><a href="../html/25.koa-1.html">25.koa-1</a></li><li><a href="../html/26.webpack-1-basic.html">26.webpack-1-basic</a></li><li><a href="../html/26.webpack-2-optimize.html">26.webpack-2-optimize</a></li><li><a href="../html/26.webpack-3.tapable.html">26.webpack-3.tapable</a></li><li><a href="../html/26.webpack-4-AST.html">26.webpack-4-AST</a></li><li><a href="../html/26.webpack-5-source.html">26.webpack-5-source</a></li><li><a href="../html/26.webpack-6-loader.html">26.webpack-6-loader</a></li><li><a href="../html/26.webpack-7-plugin.html">26.webpack-7-plugin</a></li><li><a href="../html/26.webpack-8-hand.html">26.webpack-8-hand</a></li><li><a href="../html/27.react-1.html">27.react-1</a></li><li><a href="../html/27.react-2.html">27.react-2</a></li><li><a href="../html/27.react-3.html">27.react-3</a></li><li><a href="../html/27.react-4-immutable.html">27.react-4-immutable</a></li><li><a href="../html/27.react-5-react-dom-diff.html">27.react-5-react-dom-diff</a></li><li><a href="../html/27.react-6.html">27.react-6</a></li><li><a href="../html/28.react-mobx.html">28.react-mobx</a></li><li><a href="../html/28.redux-0.html">28.redux-0</a></li><li><a href="../html/28.redux-1.html">28.redux-1</a></li><li><a href="../html/28.redux-2-中间件.html">28.redux-2-中间件</a></li><li><a href="../html/28.redux-3-saga.html">28.redux-3-saga</a></li><li class="active"><a href="../html/28.redux-jwt-back.html">28.redux-jwt-back</a></li><li><a href="../html/28.redux-jwt-front.html">28.redux-jwt-front</a></li><li><a href="../html/29.mongodb-1.html">29.mongodb-1</a></li><li><a href="../html/29.mongodb-2.html">29.mongodb-2</a></li><li><a href="../html/29.mongodb-3.html">29.mongodb-3</a></li><li><a href="../html/29.mongodb-4.html">29.mongodb-4</a></li><li><a href="../html/29.mongodb-5.html">29.mongodb-5</a></li><li><a href="../html/29.mongodb-6.html">29.mongodb-6</a></li><li><a href="../html/30.cms-1-mysql.html">30.cms-1-mysql</a></li><li><a href="../html/30.cms-2-mysql.html">30.cms-2-mysql</a></li><li><a href="../html/30.cms-3-mysql.html">30.cms-3-mysql</a></li><li><a href="../html/30.cms-4-egg.html">30.cms-4-egg</a></li><li><a href="../html/30.cms-5-api.html">30.cms-5-api</a></li><li><a href="../html/30.cms-6-roadhog.html">30.cms-6-roadhog</a></li><li><a href="../html/30.cms-7-umi.html">30.cms-7-umi</a></li><li><a href="../html/30.cms-8-dva.html">30.cms-8-dva</a></li><li><a href="../html/30.cms-9-dva.html">30.cms-9-dva</a></li><li><a href="../html/30.cms-10-front.html">30.cms-10-front</a></li><li><a href="../html/30.cms-11-deploy.html">30.cms-11-deploy</a></li><li><a href="../html/33.redis.html">33.redis</a></li><li><a href="../html/34.unittest.html">34.unittest</a></li><li><a href="../html/35.jwt.html">35.jwt</a></li><li><a href="../html/36.websocket-1.html">36.websocket-1</a></li><li><a href="../html/36.websocket-2.html">36.websocket-2</a></li><li><a href="../html/38.chat-api-1.html">38.chat-api-1</a></li><li><a href="../html/38.chat-api-2.html">38.chat-api-2</a></li><li><a href="../html/38.chat-3.html">38.chat-3</a></li><li><a href="../html/38.chat-api-3.html">38.chat-api-3</a></li><li><a href="../html/38.chat.html">38.chat</a></li><li><a href="../html/38.chat2.html">38.chat2</a></li><li><a href="../html/38.chat2.html">38.chat2</a></li><li><a href="../html/39.crawl-0.html">39.crawl-0</a></li><li><a href="../html/39.crawl-1.html">39.crawl-1</a></li><li><a href="../html/39.crawl-2.html">39.crawl-2</a></li><li><a href="../html/40.deploy.html">40.deploy</a></li><li><a href="../html/41.safe.html">41.safe</a></li><li><a href="../html/42.test.html">42.test</a></li><li><a href="../html/43.nginx.html">43.nginx</a></li><li><a href="../html/44.enzyme.html">44.enzyme</a></li><li><a href="../html/45.docker.html">45.docker</a></li><li><a href="../html/46.elastic.html">46.elastic</a></li><li><a href="../html/47.oauth.html">47.oauth</a></li><li><a href="../html/48.wxpay.html">48.wxpay</a></li><li><a href="../html/49.nunjucks.html">49.nunjucks</a></li><li><a href="../html/50.ketang.html">50.ketang</a></li><li><a href="../html/index.html">index</a></li><li><a href="../html/51.typescript.html">51.typescript</a></li><li><a href="../html/52.UML.html">52.UML</a></li><li><a href="../html/53.design.html">53.design</a></li><li><a href="../html/index.html">index</a></li><li><a href="../html/54.linux.html">54.linux</a></li><li><a href="../html/55.yaml.html">55.yaml</a></li><li><a href="../html/50.ketang2.html">50.ketang2</a></li><li><a href="../html/56.ts.html">56.ts</a></li><li><a href="../html/57.ts_react.html">57.ts_react</a></li><li><a href="../html/58.react-ssr.html">58.react-ssr</a></li><li><a href="../html/59.react-ssr.html">59.react-ssr</a></li></ul></div>


<div class="warpper">

    <div class="page-toc">
        <ul><li><a href="#t01.搭建JWT后端环境">1.搭建JWT后端环境</a></li><li><a href="#t12.启动服务">2.启动服务</a><ul><li><a href="#t22.1 app.js">2.1 app.js</a></li><li><a href="#t32.2 index.js">2.2 index.js</a></li><li><a href="#t42.3 users.js">2.3 users.js</a></li><li><a href="#t52.4 start">2.4 start</a></li></ul></li><li><a href="#t63.用户接口">3.用户接口</a><ul><li><a href="#t73.1 config.js">3.1 config.js</a></li><li><a href="#t83.2 users.js">3.2 users.js</a></li><li><a href="#t93.3 index.js">3.3 index.js</a></li><li><a href="#t103.4 user.js">3.4 user.js</a></li></ul></li><li><a href="#t114.密码加密">4.密码加密</a><ul><li><a href="#t124.1 user.js">4.1 user.js</a></li><li><a href="#t134.2 users.js">4.2 users.js</a></li></ul></li><li><a href="#t145.JWT认证">5.JWT认证</a><ul><li><a href="#t155.1 config.js">5.1 config.js</a></li><li><a href="#t165.2  models/index.js">5.2  models/index.js</a></li><li><a href="#t175.3 routes/users.js">5.3 routes/users.js</a></li><li><a href="#t185.4 jwt.js">5.4 jwt.js</a></li></ul></li><li><a href="#t196.管理员发表文章管理">6.管理员发表文章管理</a><ul><li><a href="#t206.1 app.js">6.1 app.js</a></li><li><a href="#t216.2 models/article.js">6.2 models/article.js</a></li><li><a href="#t226.3 models/users.js">6.3 models/users.js</a></li><li><a href="#t236.4 routes/articles">6.4 routes/articles</a></li><li><a href="#t246.5 routes/users.js">6.5 routes/users.js</a></li><li><a href="#t256.6 utils/jwt.js">6.6 utils/jwt.js</a></li></ul></li></ul>
    </div>
    
    <div class="content markdown-body">
        <h2 id="t01.&#x642D;&#x5EFA;JWT&#x540E;&#x7AEF;&#x73AF;&#x5883;">1.&#x642D;&#x5EFA;JWT&#x540E;&#x7AEF;&#x73AF;&#x5883; <a href="#t01.&#x642D;&#x5EFA;JWT&#x540E;&#x7AEF;&#x73AF;&#x5883;"> # </a></h2>
<pre><code class="lang-js">cnpm i express cors jsonwebtoken cookie-parser morgan mongoose bcryptjs -S
cnpm i nodemon -g
</code></pre>
<h2 id="t12.&#x542F;&#x52A8;&#x670D;&#x52A1;">2.&#x542F;&#x52A8;&#x670D;&#x52A1; <a href="#t12.&#x542F;&#x52A8;&#x670D;&#x52A1;"> # </a></h2>
<h3 id="t22.1 app.js">2.1 app.js <a href="#t22.1 app.js"> # </a></h3>
<p>app.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">const</span> cors=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;cors&apos;</span>);
<span class="hljs-keyword">const</span> path=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;path&apos;</span>);
<span class="hljs-keyword">const</span> logger=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;morgan&apos;</span>);
<span class="hljs-keyword">const</span> cookieParser=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;cookie-parser&apos;</span>);
<span class="hljs-keyword">const</span> indexRouter=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./routes/index&apos;</span>);
<span class="hljs-keyword">const</span> usersRouter=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./routes/users&apos;</span>);
<span class="hljs-keyword">const</span> app=express();
app.use(cors());
app.use(logger(<span class="hljs-string">&apos;dev&apos;</span>));
app.use(express.json());
app.use(express.urlencoded({<span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span>}));
app.use(cookieParser());
app.use(<span class="hljs-string">&apos;/&apos;</span>,indexRouter);
app.use(<span class="hljs-string">&apos;/users&apos;</span>,usersRouter);
app.listen(<span class="hljs-number">3000</span>,() =&gt; <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&apos;server started at port 3000&apos;</span>));
</code></pre>
<h3 id="t32.2 index.js">2.2 index.js <a href="#t32.2 index.js"> # </a></h3>
<p>routes/index.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">const</span> router=express.Router();
router.get(<span class="hljs-string">&apos;/&apos;</span>,<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req,res</span>) </span>{
    res.send(<span class="hljs-string">&apos;index&apos;</span>);
});
<span class="hljs-built_in">module</span>.exports=router;
</code></pre>
<h3 id="t42.3 users.js">2.3 users.js <a href="#t42.3 users.js"> # </a></h3>
<p>routes/users.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">const</span> router=express.Router();
router.get(<span class="hljs-string">&apos;/&apos;</span>,<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req,res</span>) </span>{
    res.send(<span class="hljs-string">&apos;users&apos;</span>);
});
<span class="hljs-built_in">module</span>.exports=router;
</code></pre>
<h3 id="t52.4 start">2.4 start <a href="#t52.4 start"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-string">&quot;scripts&quot;</span>: {
    <span class="hljs-string">&quot;start&quot;</span>: <span class="hljs-string">&quot;nodemon ./app.js&quot;</span>
  },
</code></pre>
<h2 id="t63.&#x7528;&#x6237;&#x63A5;&#x53E3;">3.&#x7528;&#x6237;&#x63A5;&#x53E3; <a href="#t63.&#x7528;&#x6237;&#x63A5;&#x53E3;"> # </a></h2>
<h3 id="t73.1 config.js">3.1 config.js <a href="#t73.1 config.js"> # </a></h3>
<p>config.js</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports={
    <span class="hljs-attr">PORT</span>: <span class="hljs-number">3000</span>,
    <span class="hljs-attr">DB_URL</span>:<span class="hljs-string">&quot;mongodb://localhost/userSystem&quot;</span>
}
</code></pre>
<h3 id="t83.2 users.js">3.2 users.js <a href="#t83.2 users.js"> # </a></h3>
<p>routes/users.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">const</span> User=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../models/user&apos;</span>);
<span class="hljs-keyword">const</span> router=express.Router();
router.post(<span class="hljs-string">&apos;/signup&apos;</span>,<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req,res</span>) </span>{
    <span class="hljs-keyword">let</span> user=<span class="hljs-keyword">new</span> User(req.body);
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> user.save();
        res.json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">data</span>:user
        });
    } <span class="hljs-keyword">catch</span> (error) {
        res.json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
            error
        });
    }

});
<span class="hljs-built_in">module</span>.exports=router;
</code></pre>
<h3 id="t93.3 index.js">3.3 index.js <a href="#t93.3 index.js"> # </a></h3>
<p>models/index.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> {DB_URL} = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../config&apos;</span>);
<span class="hljs-keyword">const</span> mongoose=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;mongoose&apos;</span>);
<span class="hljs-keyword">let</span> connection=mongoose.createConnection(DB_URL);
<span class="hljs-built_in">module</span>.exports=connection;
</code></pre>
<h3 id="t103.4 user.js">3.4 user.js <a href="#t103.4 user.js"> # </a></h3>
<p>models/user.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mongoose=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;mongoose&apos;</span>);
<span class="hljs-keyword">const</span> connection=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./index&apos;</span>);
<span class="hljs-keyword">const</span> Schema=mongoose.Schema;
<span class="hljs-keyword">const</span> UserSchema=<span class="hljs-keyword">new</span> Schema({
    <span class="hljs-attr">username</span>: {<span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>,<span class="hljs-attr">unique</span>: <span class="hljs-literal">true</span>},
    <span class="hljs-attr">password</span>:{<span class="hljs-attr">type</span>:<span class="hljs-built_in">String</span>}
},{<span class="hljs-attr">timestamps</span>:<span class="hljs-literal">true</span>});
<span class="hljs-keyword">const</span> User=connection.model(<span class="hljs-string">&apos;User&apos;</span>,UserSchema);
<span class="hljs-built_in">module</span>.exports=User;
</code></pre>
<h2 id="t114.&#x5BC6;&#x7801;&#x52A0;&#x5BC6;">4.&#x5BC6;&#x7801;&#x52A0;&#x5BC6; <a href="#t114.&#x5BC6;&#x7801;&#x52A0;&#x5BC6;"> # </a></h2>
<h3 id="t124.1 user.js">4.1 user.js <a href="#t124.1 user.js"> # </a></h3>
<p>models/user.js</p>
<pre><code class="lang-js">UserSchema.pre(<span class="hljs-string">&apos;save&apos;</span>,<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">next</span>) </span>{
    bcrypt.genSalt(<span class="hljs-number">10</span>,(err,salt)=&gt;{
        bcrypt.hash(<span class="hljs-keyword">this</span>.password,salt,(err,hash) =&gt; {
            <span class="hljs-keyword">this</span>.password=hash;
            next();
        });
    });
});
UserSchema.methods.comparePassword=<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">password</span>) </span>{
    <span class="hljs-keyword">return</span> bcrypt.compareSync(password,<span class="hljs-keyword">this</span>.password);
}
</code></pre>
<h3 id="t134.2 users.js">4.2 users.js <a href="#t134.2 users.js"> # </a></h3>
<p>routes/users.js</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">const</span> User=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../models/user&apos;</span>);
<span class="hljs-keyword">const</span> router=express.Router();
router.post(<span class="hljs-string">&apos;/signup&apos;</span>,<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req,res</span>) </span>{
    <span class="hljs-keyword">let</span> user=<span class="hljs-keyword">new</span> User(req.body);
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> user.save();
        res.json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
            <span class="hljs-attr">data</span>: {
                <span class="hljs-attr">id</span>: user._id,
                <span class="hljs-attr">username</span>:user.username
            }
        });
    } <span class="hljs-keyword">catch</span> (error) {
        res.json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
            error
        });
    }

});
router.post(<span class="hljs-string">&apos;/signin&apos;</span>,<span class="hljs-keyword">async</span> (req,res) =&gt; {
    <span class="hljs-keyword">const</span> {username,password}=req.body;
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> user=<span class="hljs-keyword">await</span> User.findOne({username});
        <span class="hljs-keyword">if</span> (user &amp;&amp; user.comparePassword(password)) {
            res.json({
                <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
                <span class="hljs-attr">data</span>: {
                    <span class="hljs-attr">id</span>: user._id,
                    <span class="hljs-attr">username</span>:user.username
                }
            });
        } <span class="hljs-keyword">else</span> {
            res.status(<span class="hljs-number">403</span>).json({
                <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">error</span>:<span class="hljs-string">&apos;&#x7528;&#x6237;&#x540D;&#x6216;&#x5BC6;&#x7801;&#x9519;&#x8BEF;&apos;</span>
            });
        }
    } <span class="hljs-keyword">catch</span> (error) {
        res.status(<span class="hljs-number">403</span>).json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
            error
        });
    }
})
<span class="hljs-built_in">module</span>.exports=router;
</code></pre>
<h2 id="t145.JWT&#x8BA4;&#x8BC1;">5.JWT&#x8BA4;&#x8BC1; <a href="#t145.JWT&#x8BA4;&#x8BC1;"> # </a></h2>
<h3 id="t155.1 config.js">5.1 config.js <a href="#t155.1 config.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports={
    <span class="hljs-attr">PORT</span>: <span class="hljs-number">3000</span>,
    <span class="hljs-attr">DB_URL</span>: <span class="hljs-string">&quot;mongodb://localhost:27017/userSystem&quot;</span>,
    <span class="hljs-attr">SECRET</span>:<span class="hljs-string">&quot;zfpx&quot;</span>
}
</code></pre>
<h3 id="t165.2  models/index.js">5.2  models/index.js <a href="#t165.2  models/index.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> connection=mongoose.createConnection(DB_URL,{ <span class="hljs-attr">useNewUrlParser</span>: <span class="hljs-literal">true</span> })
</code></pre>
<h3 id="t175.3 routes/users.js">5.3 routes/users.js <a href="#t175.3 routes/users.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> {sign,verify}=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../utils/jwt&apos;</span>);
router.post(<span class="hljs-string">&apos;/signin&apos;</span>,<span class="hljs-keyword">async</span> (req,res) =&gt; {
    <span class="hljs-keyword">const</span> {username,password}=req.body;
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> user=<span class="hljs-keyword">await</span> User.findOne({username});
        <span class="hljs-keyword">if</span> (user &amp;&amp; user.comparePassword(password)) {
            res.json({
                <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
                <span class="hljs-attr">data</span>: {
                    <span class="hljs-attr">token</span>:sign({<span class="hljs-attr">username</span>:user.username})
                }
            });
        } <span class="hljs-keyword">else</span> {
            res.status(<span class="hljs-number">403</span>).json({
                <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
                <span class="hljs-attr">error</span>:<span class="hljs-string">&apos;&#x7528;&#x6237;&#x540D;&#x6216;&#x5BC6;&#x7801;&#x9519;&#x8BEF;&apos;</span>
            });
        }
    } <span class="hljs-keyword">catch</span> (error) {
        res.status(<span class="hljs-number">403</span>).json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
            error
        });
    }
})
router.get(<span class="hljs-string">&apos;/signout&apos;</span>,verify,(req,res) =&gt; {
    res.json({
        <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
        <span class="hljs-attr">data</span>:<span class="hljs-string">&apos;&#x9000;&#x51FA;&#x767B;&#x5F55;&#x6210;&#x529F;!&apos;</span>
    });
});
</code></pre>
<h3 id="t185.4 jwt.js">5.4 jwt.js <a href="#t185.4 jwt.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> jwt=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;jsonwebtoken&apos;</span>);
<span class="hljs-keyword">const</span> {SECRET}=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../config&apos;</span>);
<span class="hljs-keyword">const</span> sign=<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> jwt.sign(user,SECRET,{
        <span class="hljs-attr">expiresIn</span>:<span class="hljs-number">10</span> <span class="hljs-comment">//&#x79D2;</span>
    });
}
<span class="hljs-keyword">const</span> verify=<span class="hljs-function">(<span class="hljs-params">req,res,next</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> token=req.headers.authorization;
    <span class="hljs-keyword">if</span> (token) {
        jwt.verify(token,SECRET,(err,data)=&gt;{
            <span class="hljs-keyword">if</span> (err) {
                <span class="hljs-keyword">if</span> (err.name == <span class="hljs-string">&apos;TokenExpiredError&apos;</span>) {
                    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({
                        <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
                        <span class="hljs-attr">error</span>:<span class="hljs-string">&apos;token&#x5DF2;&#x7ECF;&#x8FC7;&#x671F;!&apos;</span>
                    });
                } <span class="hljs-keyword">else</span> {
                    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({
                        <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
                        <span class="hljs-attr">error</span>:<span class="hljs-string">&apos;token&#x8BA4;&#x8BC1;&#x5931;&#x8D25;!&apos;</span>
                    });
                }
            } <span class="hljs-keyword">else</span> {
                next();
            }
        });
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">1</span>,
            <span class="hljs-attr">error</span>:<span class="hljs-string">&apos;&#x8BF7;&#x63D0;&#x4F9B;token&apos;</span>
        });
    }
}
<span class="hljs-built_in">module</span>.exports={
    sign,
    verify
}
</code></pre>
<h2 id="t196.&#x7BA1;&#x7406;&#x5458;&#x53D1;&#x8868;&#x6587;&#x7AE0;&#x7BA1;&#x7406;">6.&#x7BA1;&#x7406;&#x5458;&#x53D1;&#x8868;&#x6587;&#x7AE0;&#x7BA1;&#x7406; <a href="#t196.&#x7BA1;&#x7406;&#x5458;&#x53D1;&#x8868;&#x6587;&#x7AE0;&#x7BA1;&#x7406;"> # </a></h2>
<h3 id="t206.1 app.js">6.1 app.js <a href="#t206.1 app.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> articlesRouter=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./routes/articles&apos;</span>);
app.use(<span class="hljs-string">&apos;/articles&apos;</span>,articlesRouter);
</code></pre>
<h3 id="t216.2 models/article.js">6.2 models/article.js <a href="#t216.2 models/article.js"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mongoose=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;mongoose&apos;</span>);
<span class="hljs-keyword">const</span> connection=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;./index&apos;</span>);
<span class="hljs-keyword">const</span> Schema=mongoose.Schema;
<span class="hljs-keyword">const</span> ArticleSchema=<span class="hljs-keyword">new</span> Schema({
    <span class="hljs-attr">title</span>: {<span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>},
    <span class="hljs-attr">content</span>: {<span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>}
},{<span class="hljs-attr">timestamps</span>: <span class="hljs-literal">true</span>});

<span class="hljs-keyword">const</span> Article=connection.model(<span class="hljs-string">&apos;Article&apos;</span>,ArticleSchema);
<span class="hljs-built_in">module</span>.exports=Article;
</code></pre>
<h3 id="t226.3 models/users.js">6.3 models/users.js <a href="#t226.3 models/users.js"> # </a></h3>
<pre><code class="lang-diff"> const Schema=mongoose.Schema;
 const UserSchema=new Schema({
     username: {type: String,unique: true},
<span class="hljs-deletion">-    password:{type:String}</span>
<span class="hljs-addition">+    password: {type: String},</span>
<span class="hljs-addition">+    admin:{type:Boolean,default:false}</span>
 },{timestamps: true});
 UserSchema.pre(&apos;save&apos;,function (next) {
     bcrypt.genSalt(10,(err,salt)=&gt;{
</code></pre>
<h3 id="t236.4 routes/articles">6.4 routes/articles <a href="#t236.4 routes/articles"> # </a></h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;express&apos;</span>);
<span class="hljs-keyword">const</span> Article=<span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../models/article&apos;</span>);
<span class="hljs-keyword">const</span> {verify} = <span class="hljs-built_in">require</span>(<span class="hljs-string">&apos;../utils/jwt&apos;</span>);
<span class="hljs-keyword">const</span> router=express.Router();
router.post(<span class="hljs-string">&apos;/add&apos;</span>,verify(<span class="hljs-literal">true</span>),<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req,res</span>) </span>{
    <span class="hljs-keyword">const</span> article=<span class="hljs-keyword">new</span> Article(req.body);
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">await</span> article.save();
        res.json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
            article
        });
    } <span class="hljs-keyword">catch</span> (error) {
        res.status(<span class="hljs-number">500</span>).json({<span class="hljs-attr">code</span>:<span class="hljs-number">1</span>,error});
    }
});
router.get(<span class="hljs-string">&apos;/list&apos;</span>,verify(),<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">req,res</span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">let</span> articles=<span class="hljs-keyword">await</span> Article.find();
        res.json({
            <span class="hljs-attr">code</span>: <span class="hljs-number">0</span>,
            articles
        });
    } <span class="hljs-keyword">catch</span> (error) {
        res.status(<span class="hljs-number">500</span>).json({<span class="hljs-attr">code</span>:<span class="hljs-number">1</span>,error});
    }
});
<span class="hljs-built_in">module</span>.exports=router;
</code></pre>
<h3 id="t246.5 routes/users.js">6.5 routes/users.js <a href="#t246.5 routes/users.js"> # </a></h3>
<pre><code class="lang-diff">                 data: {
<span class="hljs-deletion">-                    token:sign({username:user.username})</span>
<span class="hljs-addition">+                    token:sign({username:user.username,admin:user.admin})</span>
                 }

</code></pre>
<h3 id="t256.6 utils/jwt.js">6.6 utils/jwt.js <a href="#t256.6 utils/jwt.js"> # </a></h3>
<pre><code class="lang-diff">const verify=(mustAdmin)=&gt;(req,res,next) =&gt; {
    const token=req.headers.authorization;
    if (token) {
        jwt.verify(token,SECRET,(err,data)=&gt;{
            if (err) {
                if (err.name == &apos;TokenExpiredError&apos;) {
                    return res.status(401).json({
                        code: 1,
                        error:&apos;token&#x5DF2;&#x7ECF;&#x8FC7;&#x671F;!&apos;
                    });
                } else {
                    return res.status(401).json({
                        code: 1,
                        error:&apos;token&#x8BA4;&#x8BC1;&#x5931;&#x8D25;!&apos;
                    });
                }
            } else {
<span class="hljs-deletion">-               next();</span>
<span class="hljs-addition">+                if (mustAdmin) {</span>
<span class="hljs-addition">+                    let {admin}=data;</span>
<span class="hljs-addition">+                    if (admin) {</span>
<span class="hljs-addition">+                        next();</span>
<span class="hljs-addition">+                    } else {</span>
<span class="hljs-addition">+                        return res.status(401).json({</span>
<span class="hljs-addition">+                            code: 1,</span>
<span class="hljs-addition">+                            error:&apos;&#x5FC5;&#x987B;&#x662F;&#x7BA1;&#x7406;&#x5458;&#x624D;&#x80FD;&#x8FDB;&#x884C;&#x6B64;&#x9879;&#x64CD;&#x4F5C;!&apos;</span>
<span class="hljs-addition">+                        });</span>
<span class="hljs-addition">+                    }</span>
<span class="hljs-addition">+                } else {</span>
<span class="hljs-addition">+                    next();</span>
<span class="hljs-addition">+                }</span>

            }
        });
    } else {
        return res.status(401).json({
            code: 1,
            error:&apos;&#x8BF7;&#x63D0;&#x4F9B;token&apos;
        });
    }
}
</code></pre>
<ul>
<li><a href="https://gitee.com/zhufengpeixun/jwt-backend">jwt-backend</a></li>
</ul>

        <div class="copyright">Powered by <a href="https://github.com/jaywcjlove/idoc" target="_blank">idoc</a>. Dependence <a href="https://nodejs.org">Node.js</a> run.</div>
    </div>
    
</div>

<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.js"></script>
<script>
$('.warpper .page-toc ul ul li a').on('click',function(){
  $('.warpper .page-toc ul ul li a').removeClass('my-active')
  $(this).addClass('my-active')
})
  // if (!$('.understand-me').length) {
  //   var bar = $(window).height() - $('.navbar ').height() - $('.page-toc').position().top;
  //   var count = bar / 26 / 2;
  //   var barHeight = $('.page-toc').outerHeight();
  //   $('.page-toc li').eq(0).children('a').addClass('red');
  //   var arr = [];
  //   $("h1,h2,h3,h4,h5,h6").each(function () {
  //     arr.push($(this).position().top);
  //   });
  //   var timer
  //   function dark() {
  //     clearTimeout(timer)
  //      timer = setTimeout(function () {
  //      var top = Math.abs($('.page-toc > ul').position().top);
  //      var cur = $('.content').scrollTop();
  //      for (var i = arr.length; i >= 0; i--) {
  //        if (arr[i] <= cur) {
  //          break;
  //        }
  //      }
  //      if (i === -1) {
  //        i = 0;
  //      }
  //      $('.page-toc li a').removeClass('red');
  //      $('.page-toc li').eq(i).children('a').addClass('red');
  //      let height = $('.page-toc li').eq(i).position().top-$('.page-toc').height(); // 如果当前的offset出去了 回到中间可好？
  //      $('.page-toc').scrollTop(height+$('.page-toc').height()/2);
  //    },200)
  //   }

  //   $('.content').on('scroll', dark);
  // }
</script>
<style>

    /* ::-webkit-scrollbar{width:14px;}
    ::-webkit-scrollbar-track{background-color:transparent;}
    ::-webkit-scrollbar-thumb{background-color:transparent;}
    ::-webkit-scrollbar-thumb:hover {background-color:transparent}
    ::-webkit-scrollbar-thumb:active {background-color:transparent} */

    .page-toc > ul .red {
        background: #f3f3f3;
        z-index: 1;
        border-left: 3px solid #009a61;
        -webkit-transition: all .2s ease;
        transition: all .2s ease;
        color: #000
    }





</style>
</body>
</html>
